/**
 * Created by admin on 2017/9/22.
 */
import {config, sandBox} from '../../../lib/myapp.js'
import Animation from '../../../utils/animation.js'
Page({
    data: {
        list: [],
        groupList: [],
        allCheck: true,
        channel: 'normal',
        loading: false,
        is_login: true,
        show_select: false,
        specs: [],
        canBuy: true,
        store_count: 0,
        price: 0,
        select_product: null,
        select_count: 0,
        skuTable: {},
        specId: null,
        commodity: {},
        meta: {},
        goodsIndex: 0,
        all: {
            count: 0
        },
        query: {
            spec: {}
        },
        text:'',
        show_search:false,
        searches: [],
        storeList:[],
        show:false,
        isAdd:false

    },

    onReady() {
        var searches = wx.getStorageSync('goods_search_history');
        if (searches.length) {
            this.setData({
                searches: searches
            })
        }
    },

    onShow(){
        var locals;
        // var locals = [{"__raw_id":"e16a112b70a0e9af002a85f1d817815f","id":23316,"name":"16秋冬新品滑雪系列 男 防水透气 保暖 夹棉外套 2TJW","qty":1,"price":"1798.00","total":"1798.00","type":"sku","status":"online","img":"http://tnf-equipment.b0.upaiyun.com/2016/10/14770466310320.jpg","size":"XL","color":"深蓝/印花/KHF","com_id":2584,"sku":"NF0A2TJWKHF10XLREG","channel":"normal","checked":true},{"__raw_id":"df371e2fd985b4caca3506445cd97e94","id":21551,"name":"  16秋冬新品女款防水透气全压胶冲锋衣2U8U","qty":2,"price":"549.00","total":"1098.00","type":"sku","status":"online","img":"http://tnf-equipment.b0.upaiyun.com/2016/07/14684833700862.jpg","size":"M","color":"月光白/128","com_id":2346,"sku":"NF0A2U8U128100M","channel":"normal","checked":true}]
        // wx.setStorageSync('cart',locals)
        var oauth = wx.getStorageSync('user_token')

        if (oauth && locals && locals.length) {
            // 提交本地购物车
            this.appendToCart(locals);
        } else {
            this.queryCartList();
        }


    },
    showSearch(){
        this.setData({
            show_search:true,
            show_select:true
        })

        var animation = new Animation('showSearch');
        animation.Pullleft()


    },
    hideSearch(){

        var animation = new Animation('showSearch');
        animation.right().then(() => {
            this.setData({
                show_search: false,
                storeList:[]
            })
        })
    },
    search(e){
        this.setData({
            text: e.detail.value,
        })
    },
// 点击单个搜索记录搜索
    searchHistory(e) {

        var searches = JSON.parse(JSON.stringify(this.data.searches));
        var keyword = searches[e.currentTarget.dataset.index];

        searches.splice(e.currentTarget.dataset.index, 1);
        searches.unshift(keyword);


        wx.setStorageSync('goods_search_history', searches);

        wx.setNavigationBarTitle({
            title: '搜索：' + "'" + keyword + "'"
        })
        this.querySearchList({keyword: keyword});

        this.setData({
            show: false,
            searches: searches,
            text: keyword
        });
    },
    // 删除单个搜索记录
    removeSearchHistory(e) {
        var searches = JSON.parse(JSON.stringify(this.data.searches));

        searches.splice(e.currentTarget.dataset.index, 1);

        wx.setStorageSync('goods_search_history', searches);

        this.setData({
            searches: searches
        })
    },
    // 清空搜索记录
    clearSearchHistory() {
        wx.removeStorageSync('goods_search_history');
        this.setData({
            show: false,
            searches:[]
        })
    },
    // 单击搜索
    searchKeywords() {

        var keyword = this.data.text;
        if (!keyword || !keyword.length) return;
        var searches = JSON.parse(JSON.stringify(this.data.searches));
        for (let i = 0, len = searches.length; i < len; i++) {
            let  search = searches[i];
            if (search === keyword) {
                searches.splice(i, 1);
                break;
            }
        }

        searches.unshift(keyword);
        wx.setStorageSync('goods_search_history', searches);

        wx.setNavigationBarTitle({
            title: '搜索：' + "'" + keyword + "'"
        })
        this.querySearchList({keyword: keyword});

        this.setData({
            show: false,
            searches: searches
        })

    },

    querySearchList(query = {}, page = 1) {
        var params = Object.assign({}, query, { page });

        wx.showLoading({
            title: '加载中',
            mask: true
        });

        sandBox.get({
            api: 'api/store/list',
            data: params,
        }).then(res =>{
            res = res.data;

            if (res.status) {
                // var keyReg = new RegExp('(' + this.data.text + ')(?!</i>)', 'g')
                // list.forEach(item => {
                // 	item.name = item.name.replace(keyReg, '<i>$1</i>');
                // })
                this.setData({
                    [`storeList.${page - 1}`]: res.data,
                    meta: res.meta
                })

            } else {
                wx.showModal({
                    title: '',
                    content: res.message
                })
            }
            wx.hideLoading();
        }).catch(rej =>{
            wx.showModal({
                title: '',
                content: '请求失败，请稍后重试'
            })
            wx.hideLoading();
        })
    },
    //搜索商品
    searchKeywords() {

        var keyword = this.data.text;
        if (!keyword || !keyword.length) return;
        var searches = JSON.parse(JSON.stringify(this.data.searches));
        for (let i = 0, len = searches.length; i < len; i++) {
            let  search = searches[i];
            if (search === keyword) {
                searches.splice(i, 1);
                break;
            }
        }

        searches.unshift(keyword);
        wx.setStorageSync('goods_search_history', searches);

        wx.setNavigationBarTitle({
            title: '搜索：' + "'" + keyword + "'"
        })
        this.querySearchList({keyword: keyword});

        this.setData({
            show: false,
            searches: searches
        })

    },
    showSpec(e){
        var id = e.currentTarget.dataset.id
        this.setData({
            isAdd:true
        })
        this.getGoodsDetail({
            api: `api/store/detail/${id}`,
            data: {include: 'photos,products,oneComment,guessYouLike,whoLike,point'}
        }).then(() => {
            this.queryCommodityStore(id)
            this.showSelect()
        })
    },
    scanCode() {
        wx.scanCode({
            onlyFramCamera:false,
            success:(res) =>{
                console.warn(res)
        var oauth = wx.getStorageSync('user_token');
        sandBox.get({
            api: `api/O2O/store/code/123456`,
            header: {Authorization: oauth}
        }).then((response) => {

            var data = response.data.data

            this.getGoodsDetail({
                api: `api/store/detail/${data.goods_id}`,
                data: {include: 'photos,products,oneComment,guessYouLike,whoLike,point'}
            }).then(() => {

                console.log(data.store_nums)
                var goods = {
                    id: data.sku_id,
                    name: data.name,
                    qty: 1,
                    // store_count: this.data.commodity.store,
                    price: data.sell_price,
                    attributes: {
                        img: data.img,
                        size: data.specsText.split(' ')[1],
                        color: data.specsText.split(' ')[0],
                        com_id: data.goods_id,
                        sku:data.sku,

                    }
                }

                if (wx.getStorageSync('user_token')) {
                    this.appendToCart(goods);
                    this.addStoreNum();
                } else {
                    goods.local = true;
                    goods.total = Number(goods.qty) * Number(goods.price);
                    goods.color = goods.attributes.color;
                    goods.size = goods.attributes.size;
                    goods.img = goods.attributes.img;


                    var locals = wx.getStorageSync('cart') || [];
                    locals.unshift(goods);

                    var skus = {};
                    var save = [];

                    locals.forEach(v => {
                        let sku, index;
                        if (v.attributes && v.attributes.sku) {
                            sku = v.attributes.sku;
                        } else {
                            sku = v.id;
                        }

                        if (skus[sku] === undefined) {
                            index = save.length;
                            v.index = index;
                            v.checked = true;
                            save.push(v);
                            skus[sku] = index;

                        } else {
                            let i = skus[sku];
                            save[i].qty += v.qty;
                            save[i].total += v.total;
                            save[i].store_count = this.data.store_count;

                        }
                    });

                    console.log(skus, save)

                    wx.setStorageSync('cart', save);

                    this.setData({
                        store_num: 0
                    })

                    this.addStoreNum();
                    this.addCart(true)
                }
            })

        })
        },
        fail:() =>{}

        })
    },
    selectSpec(e){

        var spec = {
            key: e.currentTarget.dataset.key,
            index: e.currentTarget.dataset.index,
            disabled: Number(e.currentTarget.dataset.disabled),
            active: Number(e.currentTarget.dataset.active),
            id: Number(e.currentTarget.dataset.id)
        };

        if (spec.disabled) return;
        var specs = this.data.specs;
        if (!spec.active) {
            for (let item of specs[spec.index].values) {
                if (item.active) {
                    item.active = false;
                    break;
                }
            }
        }

        specs[spec.index].values[spec.key].active = !specs[spec.index].values[spec.key].active
        spec.active = !spec.active;
        specs[spec.index].select = spec.active ? spec.id : '';


        this.setData({
            specs: specs
        })
        var canBuy = this.disallow_cart()
        this.setData({
            canBuy: canBuy
        })
        // this.queryCommodityStore(id, spec.index);
        this.specStore(this.data.result, spec.index)
    },
    specStore(result, key) {

        var data = result.data;
        var specs = this.data.specs;

        if (key === undefined) {

            specs.forEach(spec => {

                for (let v of spec.values) {
                    v.disabled = !data[v.id] || data[v.id].count == 0;
                }
            });


            this.setData({
                specs: specs,
                skuTable: result.table
            })

            var canBuy = this.disallow_cart()


            this.setData({
                canBuy: canBuy
            })

            console.log(specs)
            var count = 0;
            specs.forEach(spec => {
                count++

                if (this.data.specId && !spec.select) {

                    let ids = []
                    var skuTable = this.data.skuTable;
                    Object.keys(skuTable).forEach((v) => {
                        if (skuTable[v].id == this.data.specId) {
                            ids = count ? skuTable[v].ids.reverse() : skuTable[v].ids
                        }
                    })

                    console.log(ids)

                    for (let v of spec.values) {
                        var id = ids[v.index];
                        if (v.id == id && !v.disabled && data[v.id] && data[v.id].count) {
                            v.active = true;
                            spec.select = v.id;
                            this.setData({
                                specs: specs
                            })

                            specs = this.data.specs

                            var canBuy = this.disallow_cart()


                            this.setData({
                                canBuy: canBuy,
                            })


                            this.specStore(result, v.index)

                            return;
                        }


                    }
                }

                if (!spec.select) {
                    for (let v of spec.values) {

                        if (!v.disabled && data[v.id] && data[v.id].count) {
                            v.active = true;
                            spec.select = v.id;
                            this.setData({
                                specs: specs
                            })
                            specs = this.data.specs
                            var canBuy = this.disallow_cart()


                            this.setData({
                                canBuy: canBuy
                            })

                            // this.$emit('specStore', result, v.index);
                            this.specStore(result, v.index)

                            return;
                        }
                    }
                    return
                }

                this.setData({
                    specs: specs
                })

            });


            return;
        }

        var spec = specs[key];
        if (spec.select) {
            this.setData({
                store_count: data[spec.select].count
            })

            for (let i = 0; i < specs.length; i++) {

                if (i === key) continue;
                specs[i].values.forEach(v => {

                    v.disabled = !data[spec.select].specs[v.id].count;

                });


                if (specs[i].select) {
                    this.setData({
                        store_count: data[spec.select].specs[specs[i].select].count,
                    })
                }

                this.setData({
                    specs: specs
                })
            }
        } else {

            this.setData({
                store_count: this.data.commodity.store
            })


            for (let i = 0; i < specs.length; i++) {

                if (i === key) continue;

                specs[i].values.forEach(v => {
                    v.disabled = !data[v.id] || !data[v.id].count;
                });


                if (specs[i].select) {
                    this.setData({
                        store_count: data[specs[i].select].count,
                    })

                }

                this.setData({
                    specs: specs
                })


            }

        }

        if (parseInt(this.data.select_count) > this.data.store_count) {
            this.setData({
                select_count: String(this.data.store_count)
            })

        } else if (parseInt(this.data.select_count) === 0) {
            this.setData({
                select_count: '1'
            })
        }
        this.setData({
            specs: specs,
        })


        var canBuy = this.disallow_cart()


        this.setData({
            canBuy: canBuy
        })
    },
    modifyCount(e){

        var val = parseInt(e.detail.value);
        if (!val) {
            val = 1;
        } else if (!/^[1-9]\d*$/.test(val)) {
            val = val.replace(/[^\d].*$/, '');
            val = parseInt(val) || 1;
        }

        if (val < 0) {
            val = 1;
        } else if (val > this.data.store_count) {
            wx.showToast({
                title: '超过最大库存'
            })
            val = parseInt(this.data.store_count);
        }

        this.setData({
            select_count: val
        })

    },
    changeCount(e){

        var select_count = parseInt(this.data.select_count)

        var index = e.target.dataset.index
        var val = select_count + (parseInt(index) ? 1 : -1)

        if (val > 0 && val <= parseInt(this.data.store_count)) {
            this.setData({
                select_count: val
            })


        } else {
            wx.showToast({
                title: '超出最大库存',
                image: '../../../assets/image/error.png'
            })
        }
    },
    removeFromCart(e){
        // var oauth = this.data.is_login;
        var oauth = wx.getStorageSync('user_token');
        var index = e.target.dataset.index;
        var list = this.data.list;
        var data = list[index]
        var that = this;

        sandBox.ajax({
            api: `api/shopping/cart/${data.__raw_id}`,
            header: {Authorization: oauth},
            method: 'DELETE',
        }).then(res => {
            res = res.data;
            if (res.status) {
                that.removed(true, index)
            } else {
                that.removed(false)
            }

        }).catch(rej => {
            that.removed(false)
        })
    },

    removed (success, index){
        if (success) {

            this.queryCartList()
            // var list = this.data.list
            // var product = list.splice(index, 1)[0];
            // this.setData({
            //     list: list
            // })



            this.closeSelect()
            this.select_products()
            this.groupList();

        } else {
            wx.showToast({
                title: '删除购物车商品失败！',
                image: '../../../assets/image/error.png'
            })
        }
    },
    editGoods(e){

        const [id, index, size, qty, list, specId] = [e.target.dataset.id, e.target.dataset.index, e.target.dataset.size, e.target.dataset.qty, this.data.list, e.target.dataset.specid]


        list.forEach((v, i) => {
            i == index ? v.edit = true : v.edit = false
        })
        this.setData({
            list: list,
            goodsIndex: index,
            specId: specId
        })
        this.showSelect()
        this.getGoodsDetail({
            api: `api/store/detail/${id}`,
            data: {include: 'photos,products,oneComment,guessYouLike,whoLike,point'}
        }).then(() => {
            this.queryCommodityStore(id)
        })
    },

    showSelect(e){
        this.setData({
            show_select: false
        })


        var animation = new Animation('show');
        animation.positionInit()

        new Animation('black').show()
    },
    closeSelect(){
        var list = this.data.list;
        list.forEach((v) => {
            v.edit = false
        })

        var animation = new Animation('show');
        new Animation('black').hide()
        animation.up().then(() => {
            this.setData({
                show_select: true,
                list: list
            })
        })


    },

    addSearchGoods(){
        var data = this.data.select_product
        var goods = {
            id: data.id,
            name: this.data.commodity.name,
            qty: 1,
            // store_count: this.data.commodity.store,
            price: data.price,
            attributes: {
                img: data.img,
                size: data.size,
                color: data.color,
                com_id: this.data.commodity.id,
                sku:data.sku,

            }
        }


        this.appendToCart(goods);
        this.addStoreNum();

    },

    disallow_cart() {
        if (!this.data.specs.length) {
            return !this.data.store_count;
        }

        var ids = [], select_product = {}, specs = this.data.specs;
        for (let spec of specs) {
            if (!spec.select) {
                this.setData({
                    price: this.data.commodity.sell_price,
                    select_product: null
                })
                return true;
            }

            ids.push(spec.select);
            for (let v of spec.values) {
                if (v.id === spec.select) {
                    switch (spec.id) {
                        case 2:
                            select_product.img = v.img;
                            select_product.color = v.alias || v.value;
                            select_product.bac = v.color
                            break;
                        default:
                            select_product.size = v.value;
                            select_product.bac = v.color
                    }

                    break;
                }
            }
        }

        if (this.data.skuTable) {
            ids = ids.sort((a, b) => a > b).join('-');
            select_product = Object.assign(select_product, this.data.skuTable[ids]);
        }

        this.setData({
            price: select_product.price,
            select_product: select_product
        })

        return false;
    },

    appendToCart(data) {
        var oauth = wx.getStorageSync('user_token');
        if (!oauth) return;

        if (!Array.isArray(data)) {
            data = [data];
        }

        console.log(data)

        var json = {};
        data.forEach((v, i) => json[i] = v);
        data = json;

        sandBox.post({
            api: `api/shopping/cart`,
            data: data,
            header: {Authorization: oauth},

        }).then(res => {
            res = res.data;
            if (res.status) {
                this.addCart(true)
            } else {
                this.addCart(false, res.message)
            }
        }).catch(rej => {
            this.addCart(false)
        })
    },
    updateToCart(data, id) {
        var oauth = wx.getStorageSync('user_token');
        if (!oauth) return;

        // if (!Array.isArray(data)) {
        //     data = [data];
        // }
        //
        // var json = {};
        // data.forEach((v, i) => json[i] = v);
        // data = json;

        sandBox.ajax({
            api: `api/shopping/cart/${id}`,
            method: 'PUT',
            data: data,
            header: {Authorization: oauth},

        }).then(res => {
            res = res.data;
            if (res.status) {

                this.addCart(true)
            } else {
                this.addCart(false, res.message)
            }
        }).catch(rej => {

        })
    },
    addCart(success, message) {
        // this.$refs.button.finish();
        this.setData({
            loading: false,

        })
        if (success) {

            wx.removeStorageSync('cart')

            // TODO
            //this.$emit('readyCheckout');
            if (this.data.isAdd) {
                this.setData({
                    isAdd:false,
                    text:''
                })

                this.hideSearch()
            }
            this.queryCartList();

        } else {

            wx.showModal({
                title: message || '保存本地购物车失败,请重试！'

            })
            this.closeSelect()
            this.select_products()
            this.groupList()
        }


    },
    queryCartList () {

        var data = wx.getStorageSync('cart') || [];
        // var oauth = Cache.get(cache_keys.token);
        var oauth = wx.getStorageSync('user_token');
        if (!oauth) {
            this.setData({
                list: data
            })
            this.closeSelect();
            this.select_products()
            this.groupList()

            return
        }

        sandBox.get({
            api: `api/shopping/cart`,
            header: {Authorization: oauth},

        }).then(res => {
            console.log(res)
            res = res.data
            var data = []

            if (res.status && res.code === 200 && res.data) {
                data = Object.keys(res.data).map(key => {
                    res.data[key].edit = false;
                    res.data[key].checked = true;
                    return res.data[key];
                }).concat(data);


            }




            console.log(data.length)
            if (!data.length) wx.removeStorageSync('select_member');
            this.setData({
                list: data
            })
            this.closeSelect()
            this.select_products()

            this.groupList()

        }).catch(() => {
            wx.showModal({
                content:'获取购物车数据失败'
            })
        })
    },

    confirm(){

        if (this.disallow_cart()) return;

        this.setData({
            loading: true
        })
        var select_product = this.data.select_product;
        var select_count = parseInt(this.data.select_count)
        var goodsIndex = this.data.goodsIndex
        var list = this.data.list

        var rawId = list[goodsIndex].__raw_id


        var data = this.data.specs.length ? {



            attributes: {
                img: select_product.img,
                size: select_product.size,
                color: select_product.color,
                com_id: this.data.commodity.id,
                qty: select_count,
                id: select_product.id,
                name: this.data.commodity.name,
                store_count: this.data.store_count,
                price: select_product.price,
            }
        } : {

            attributes: {
                img: this.data.commodity.img,
                com_id: this.data.commodity.id,
                id: this.data.commodity.id,
                name: this.data.commodity.name,
                qty: select_count,
                store_count: this.data.store_count,
                price: this.data.commodity.price,
            }
        };


        // if (this.channel) data.attributes.channel = 'employee';
        if (select_product.sku) data.attributes.sku = select_product.sku;


        // 判断是否登录
        // var is_login = !!Cache.get(cache_keys.token);
        var is_login = wx.getStorageSync('user_token')
        if (is_login) {
            this.updateToCart(data, rawId);
            this.addStoreNum();
        } else {
            data.local = true;
            data.total = Number(data.qty) * Number(data.price);
            data.color = data.attributes.color;
            data.size = data.attributes.size;
            data.img = data.attributes.img;

            var locals = wx.getStorageSync('cart') || [];
            locals.splice(goodsIndex, 1);
            locals.unshift(data);


            var skus = {};
            var save = [];
            locals.forEach(v => {
                let sku, index;
                if (v.attributes && v.attributes.sku) {
                    sku = v.attributes.sku;
                } else {
                    sku = v.id;
                }

                if (skus[sku] === undefined) {
                    index = save.length;
                    v.index = index;
                    v.checked = true;
                    save.push(v);
                    skus[sku] = index;

                } else {
                    let i = skus[sku];
                    save[i].qty += v.qty;
                    save[i].total += v.total;
                    save[i].store_count = this.store_count;

                }
            });
            console.log(skus, save)

            wx.setStorageSync('cart', save);

            this.setData({
                store_num: 0
            })
            this.addStoreNum();
            this.addCart(true)
        }
    },
    queryShoppingCount(){
        // var oauth = this.data.is_login
        var oauth = wx.getStorageSync('user_token');

        sandBox.get({
            api: `api/shopping/cart/count`,
            header: {Authorization: oauth},
        }).then(res => {

        }).catch(rej => {

        })
    },
    addStoreNum() {

        // 判断是否登录
        var oauth = wx.getStorageSync('user_token');
        // var cache_store_num = Cache.get(cache_keys.cart);
        var cache_store_num = wx.getStorageSync('cart')
        if (oauth) {
            this.queryShoppingCount();
        } else {
            if (cache_store_num && cache_store_num.length) {
                var store_num = this.data.store_num;
                cache_store_num.forEach(v => {

                    store_num += v.qty;
                })

                this.setData({
                    store_num: store_num
                })
            }
        }
    },
    // confirm(e){
    //
    //     var select_product = this.data.select_product,
    //         index = this.data.goodsIndex,
    //         list = this.data.list,
    //         product = {
    //             color:select_product.color,
    //             price:select_product.price,
    //             img:select_product.img,
    //             size:select_product.size,
    //             id:select_product.id,
    //             qty:this.data.select_count,
    //             sku:select_product.sku,
    //             total: String((Number(select_product.price) * this.data.select_count).toFixed(2))
    //         }
    //
    //         list[index] = Object.assign({},list[index],product)
    //
    //         this.setData({
    //             list:list
    //         })
    //
    //         wx.setStorageSync('cart',list)
    //
    //
    //         this.closeSelect()
    //         this.select_products()
    //         this.groupList()
    //
    //
    //
    // },
    select_products() {
        var data = {
            count: 0,
            total: 0,
            __ids: []
        }

        this.data.list.forEach((v) => {
            if (v.checked) {
                data.count += parseInt(v.qty);
                data.total += Number(v.total);
                data.__ids.push(v.__raw_id || v.index);
            } else {
                this.setData({
                    allCheck: false
                })
            }
        })

        this.setData({
            all: data
        })
    },
    getGoodsDetail (obj) {
        var that = this;
        return new Promise((resolve, reject) => {
            sandBox.get(obj)
                .then(res => {
                    res = res.data;
                    that.setData({
                        commodity: res.data,
                        meta: res.meta
                    })
                    resolve()
                })
                .catch(err => {
                    console.log(err);
                    reject()
                })
        })

    },
    groupList() {
        if (this.data.list) {
            var data = [];
            var groups = {};

            this.data.list.forEach((v, i) => {
                let channel = v.channel || 'normal';
                if (groups[channel] !== undefined) {
                    data[groups[channel]].items.push(v);
                    data[groups[channel]].index.push(i);
                } else {
                    groups[channel] = data.length;
                    data.push({
                        channel,
                        items: [v],
                        checked: [],
                        index: [i],
                    });
                }
            });
        }

        this.setData({
            groupList: data
        })
    },

    queryCommodityStore(id, key){
        var that = this;
        var oauth = wx.getStorageSync('user_token')
        sandBox.get({api: `api/O2O/store/${id}/edit`, header: {Authorization: oauth},})
            .then(res => {

                res = res.data
                if (!res.status || !res.data || !res.data.specs) return;
                if (res.data.specs && typeof key === 'undefined') {
                    let specs = [];

                    Object.keys(res.data.specs)
                        .forEach((key, index) => {
                            let value = res.data.specs[key];
                            value.select = '';
                            value.values = value.list
                                .map(v => {
                                    return Object.assign({
                                        index: index,
                                        active: false,
                                        disabled: false
                                    }, v);
                                });

                            delete value.list;
                            specs.push(value);
                        });

                    that.setData({
                        specs: specs
                    })

                    console.log(specs)

                    var canBuy = this.disallow_cart()


                    this.setData({
                        canBuy: canBuy
                    })
                }


                if (res.data.stores) {
                    let data = {};
                    Object.keys(res.data.stores)
                        .forEach(key => {
                            let value = res.data.stores[key];

                            value.ids.forEach(id => {
                                data[id] = data[id] || {count: 0, specs: {}};
                                data[id].count += parseInt(value.store);

                                value.ids.forEach(i => {
                                    if (i === id) return;

                                    data[id].specs[i] = {
                                        count: parseInt(value.store)
                                    };
                                })
                            });
                        });
                    // console.log(data);
                    var result = {data, table: res.data.stores};

                    this.setData({
                        result: result
                    })
                    that.specStore(result, key)
                    // this.$emit('specStore', result, key);
                }

            })
            .catch(err => {

            })
    },

    order(){
        var data = this.data.all;
        if (!data.count) {
            this.setData({
                loading: false
            })
            return
        }

        this.setData({
            loading: true
        })
        var oauth = wx.getStorageSync('user_token');
        if (!oauth) {
            // 滚去登录
            this.setData({
                loading: false
            })
            // this.$router.go({ name: 'user-quick-login', query: { source: this.$route.path } });
            wx.navigateTo({
                url: '/pages/user/register/register'
            })
            return;
        }

        var locals = wx.getStorageSync('cart');

        if (locals && locals.length) {

            // 提交本地购物车
            this.appendToCart(locals);
            return;
        }

        this.readyCheckout()
    },

    readyCheckout() {
        var ids = this.data.all.__ids;
        var type = this.data.channel;
        this.checkoutOrder(ids, type);
    },
    checkoutOrder(ids, type){
        // var oauth = this.data.is_login;
        var select_member = wx.getStorageSync('select_member')

        if (!select_member) {
            this.setData({
                loading: false
            })
            var route = getCurrentPages()[getCurrentPages().length - 1].route
            wx.navigateTo({
                url: `/pages/member/list/list?url=${route}`
            })

            return
        }

        var data = this.data.list.map((item) => {

            return {
                id: item.id,
                name: item.name,
                qty: item.qty,
                price: item.price,
                total: item.total,
                img: item.img,
                attributes: {
                    dynamic_sku: {
                        id: item.id,
                        color: item.color,
                        size: item.size
                    }
                }
            }
        })

        var json = {};
        data.forEach((v, i) => json[i] = v);
        data = json;

        var oauth = wx.getStorageSync('user_token');


        sandBox.post({
            api: `api/O2O/shopping/order/checkout?user_id=${select_member.user_bind.user.id}`,
            data: data,
            header: {Authorization: oauth},
            method: 'POST',
        }).then(res => {
            res = res.data;
            if (res.code == 200) {
                // Cache.set(cache_keys.order, res.data);
                wx.setStorageSync('local_order', res.data)
                this.checkout(true)
            } else {
                this.checkout(false, res.code || '库存数量不够');
            }
        }).catch(() => {
            wx.hideLoading()
        })


    },

    checkout (success, message) {
        this.setData({
            loading: false
        })
        // this.$refs.button.finish();
        if (success) {

            // this.$router.go({ name: 'store-order'});

            wx.navigateTo({
                url: '/pages/store/order/order',
            })

        } else {
            // this.$Alert(message || '结算失败，请重试!');
            wx.showToast({
                title: '结算失败,请重试！',
                image: '../../../assets/image/error.png'
            })
        }
    },

})

